<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2. 状态模式典型应用之“点赞”</title>
</head>
<body>
    <div id="root"></div>
    <script>
        let likeState = {
            render:function(element) {
                element.innerHTML = '赞'
            }
        };
        let unlikeState = {
            render:function(element) {
                element.innerHTML = '取消'
            }
        };
        class Button {
            constructor(root){
                this.flag = false;
                this.state = likeState;
                this.element = document.createElement('Button');
                root.appendChild(this.element);
                this.render(this.element);
            };
            setState(state) {
                this.state = state;
                this.render(this.element);
            }
            render(element){
                this.state.render(element);
            }
        };

        let btn = new Button(document.getElementById('root'));
        btn.element.addEventListener('click', function(){
            btn.flag = !btn.flag;
            btn.flag ? btn.setState(unlikeState) : btn.setState(likeState);
        })
    </script>
    
</body>
</html>
